package com.stu.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.mapper.ProductMapper;
import com.stu.pojo.Cart;
import com.stu.pojo.Product;
import com.stu.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public Product getById(Integer proId) {
        String key = "product_"+proId;
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        Boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey){
            Product product = (Product) operations.get(key);
            return product;
        }else {
            Product product = productMapper.selectById(proId);
            operations.set(key,product);
            return product;
        }
    }

    @Override
    public List<Product> getHotProduct() {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("product_price");
        wrapper.select("product_id","product_name","product_main_img");
        Page<Product> page = new Page<>(1,3);
        Page<Product> productPage = productMapper.selectPage(page, wrapper);
        List<Product> productList = productPage.getRecords();
        return productList;
    }

    @Override
    public List<Product> getListByCart(List<Cart> cartList) {
        List<Product> productList = new ArrayList<>();
        for (Cart cart:cartList){
            Product product = productMapper.selectById(cart.getProductId());
            productList.add(product);

        }
        return productList;
    }

    @Override
    public List<Product> getAll() {
        List<Product> productList = productMapper.selectList(null);
        return productList;
    }

    @Override
    public int addProduct(Product product, Integer userId) {
        product.setYy(userId); // 设置商家ID
        product.setProductStatus(0); // 默认状态为未审核
        product.setProductVersion(1); // 设置商品版本为1
        product.setProductSold(0);  // 设置商品销量为0
        return productMapper.insert(product);
    }

    @Override
    public int deleteProduct(Integer proId) {
        return productMapper.deleteById(proId);
    }
}
